# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=itstool
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.0.7
pkgrel=1
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
pkgdesc="XML to PO and back again (mingw-w64)"
url="https://itstool.org/"
msys2_repository_url='https://github.com/itstool/itstool'
license=("spdx:GPL-3.0-or-later")
depends=("${MINGW_PACKAGE_PREFIX}-python"
         "${MINGW_PACKAGE_PREFIX}-libxml2")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-setuptools"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-cc")
options=('!strip')
source=("https://files.itstool.org/itstool/${_realname}-${pkgver}.tar.bz2"
        "0001-Fix-the-crash-from-912099.patch"
        "0002-Fix-insufficiently-quoted-regular-expressions.patch"
        'reloc.patch'
        'pyscript2exe.py')
sha256sums=('6b9a7cd29a12bb95598f5750e8763cee78836a1a207f85b74d8b3275b27e87ca'
            'b43cea38118aaefa6724136d142dcc7099cd6de04cf2e226f53d4310dfe207cc'
            '4e64a2e884f9d4cbc493732fcbde9f1d5bed534f9a66330bbcc1cbeb54808c1e'
            'f292bcd116da4ea36ee9c42e206dbd9151d147da1ef5a078e743fc9ed0a4ab47'
            'e57174517b08cf8f9fb4f43a381d342d23d2db3cad661107f35ca21c39b5734d')

_apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -p1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"

  _apply_patch_with_msg \
    0001-Fix-the-crash-from-912099.patch \
    0002-Fix-insufficiently-quoted-regular-expressions.patch \
    reloc.patch

  autoreconf -fvi
}

build() {
  mkdir -p "build-${MSYSTEM}" && cd "build-${MSYSTEM}"

  PYTHON="${MINGW_PREFIX}/bin/python3" \
    ../${_realname}-${pkgver}/configure \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --build=${MINGW_CHOST} \
    --prefix=${MINGW_PREFIX}

  make
}

check() {
  cd "build-${MSYSTEM}"

  make check
}

package() {
  cd "build-${MSYSTEM}"

  make DESTDIR="${pkgdir}" install

  ${MINGW_PREFIX}/bin/python "${srcdir}/pyscript2exe.py" "${pkgdir}${MINGW_PREFIX}/bin/itstool"
  local _PRE_WIN="$(cygpath -m ${MINGW_PREFIX})"
  sed -e "s|${_PRE_WIN}|${MINGW_PREFIX}|g" \
    -i "${pkgdir}${MINGW_PREFIX}"/bin/itstool-script.py
}
